/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"075F0599-959C-4576-A636-0B363E1A3309",variableType:4}
 */
var fanio = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"611CB9C2-17BD-4694-B7AC-D64771835074",variableType:4}
 */
var fmes = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"506C6A59-921E-4391-968D-8A9766872B9D",variableType:4}
 */
var fImpresion = 0;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"E983513F-D9BA-44B5-8AC5-9C78B531A264",variableType:4}
 */
var fcentro = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"D46661BC-CD00-4444-8E77-C44FDA6D26FB",variableType:4}
 */
var fcuantos;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"39E10D8F-2174-4862-9B23-2188DE821258",variableType:4}
 */
var fcuenta = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"E4FC56FF-9F8A-4F63-9FC7-D7C7184BB86B",variableType:8}
 */
var fdif = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"D37C341B-E484-4EA7-9085-357928625786",variableType:4}
 */
var fdivision = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"C725BB6B-C19E-4A1A-9658-89858883CCD2",variableType:8}
 */
var fdolar;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"BC1176C9-15CD-4775-8649-18AEFD1C97BE",variableType:4}
 */
var fSalir;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"04AA5752-9420-4E7C-A303-1817BD11768D",variableType:8}
 */
var ftotal = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"AF1F3518-5FAA-4DF5-AA3B-7A8BA0D35C08",variableType:8}
 */
var ftotdol = null;

/**
 * Callback method for when form is shown.
 *
 * @param {Boolean} [firstShow] form is shown first time after load
 * @param {JSEvent} [event] the event that triggered the action
 *
 * @properties={typeid:24,uuid:"58315AC0-55A2-4BAC-A283-00F468B073A3"}
 * @AllowToRunInFind
 */
function onShow(firstShow, event) {
	if (fImpresion == 0)
	{
		fSalir = 0
	    globals.gtotal_debe  = 0
		globals.gtotal_haber = 0
		if (foundset.getSize() > 0)
		{
		    controller.loadRecords(null)   
		} 
	}
	fImpresion = 0
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"7C2A7678-8E07-44C8-BC43-2C08216FD15E"}
 * @AllowToRunInFind
 */
function onAction_habilita(event) {
	globals.gtotal_debe  = 0
	globals.gtotal_haber = 0
	elements.tabs_80.removeAllTabs()	
	fmes  = gejercicio_to_ejercicios.fecha_fin.getMonth()
	fanio = gejercicio_to_ejercicios.fecha_fin.getFullYear()
	/** @type {JSFoundSet<db:/contable/numcon>} */
	var fs_numcon = databaseManager.getFoundSet('contable','numcon')
	var estado = fs_numcon.find()
	if (estado == false)
	{
		globals.DIALOGS.showWarningDialog('Aviso',"Error al hacer el find","Ok") 
		return
	}
	fs_numcon.empresa 	= globals.gUservID
	fs_numcon.anio 		= fanio
    fs_numcon.mes  		= fmes
	var cuantos = fs_numcon.search()
	if (cuantos == 0 || fs_numcon.marca_cierre == 1)
	{
    	globals.DIALOGS.showWarningDialog('Aviso',"Mes inhabilitado","Ok") 		    	
		return
	}	
	/*	var params = {
         processFunction: AsientoCierre,
         message: 'Generando Asiento...', 
         opacity: 0.5,
         paneColor: '#d1fcd7',
         textColor: '#408080',
         showCancelButton: false
	};*/
	try
	{
		//plugins.busy.block( params );
		fSalir = AsientoCierre()
	}
	catch (e)
	{
		globals.DIALOGS.showWarningDialog('Aviso','Ocurrió un error en el proceso','OK')
	}
}

/**
 * @properties={typeid:24,uuid:"0CDADFF8-2C91-43F5-AB8E-41ADB4343B3E"}
 */
function GraboItem(totpes, totdol) {
	limbo_cab_to_limbo.newRecord()
	limbo_cab_to_limbo.cuentas_id = fcuenta
	limbo_cab_to_limbo.division   = fdivision
	limbo_cab_to_limbo.centro     = fcentro
	limbo_cab_to_limbo.leycod     = 0
	limbo_cab_to_limbo.leyenda    = "Asiento de Cierre"
	if (totpes  < 0)
	{
		limbo_cab_to_limbo.columna = "H"
		limbo_cab_to_limbo.impodol = totdol * (-1)
		limbo_cab_to_limbo.importe = totpes * (-1)
		globals.gtotal_haber = globals.gtotal_haber + (totpes * (-1))
	}
	else 
	{
		limbo_cab_to_limbo.columna = "D" 		
		limbo_cab_to_limbo.impodol = totdol 
		limbo_cab_to_limbo.importe = totpes 		
		globals.gtotal_debe = globals.gtotal_debe + totpes
	}
	ftotal  += totpes
	ftotdol += totdol
}

/**
 * Handle hide window.
 *
 * @param {JSEvent} [event] the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"82B1A7B5-4406-4288-BD58-D4C2C2195B08"}
 */
function onHide(event) {
	if (fSalir == 1)
	{
		var res = globals.DIALOGS.showQuestionDialog('','Esta seguro que desea Salir?','SI','NO')    	
		if (res == 'NO')
		  {
			return false
		  }
		  else
		  {
	     	databaseManager.revertEditedRecords()
		    databaseManager.setAutoSave(true)
		    return true
	   	  }		
	}
	return true
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"84389D36-FEAF-4277-824C-B1F2FB2CCECF"}
 */
function onAction_cancelar(event) {
	onHide()
	globals.gtotal_debe  = 0
	globals.gtotal_haber = 0
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"5CC012E9-FF06-48DD-AC8C-FD8DE7727114"}
 * @AllowToRunInFind
 */
function onAction_confirmar(event) {
	var res = globals.DIALOGS.showQuestionDialog('','Actualiza el asiento?','SI','NO')
	if (res == 'NO')
    {
       return 
    } 
	var error = 0
	
	for (var i = 1 ; i <= forms.asiento_cierre_det.controller.getMaxRecordIndex(); i++)
	{
		forms.asiento_cierre_det.controller.setSelectedIndex(i)
		
		if (forms.asiento_cierre_det.cuentas_id == null || forms.asiento_cierre_det.division == null || forms.asiento_cierre_det.centro == null)
		{
			error = 1
			globals.DIALOGS.showWarningDialog('Aviso',"Existen campos sin completar","Ok")					
			break
		}
	}	
	if (utils.numberFormat(globals.gtotal_debe,2) != utils.numberFormat(globals.gtotal_haber,2))
	{
		error = 1
		globals.DIALOGS.showWarningDialog('Aviso',"El Total del Debe no coincide con el Total del Haber","Ok")
	}
	if (error == 0)  
	{
		/** @type {JSFoundSet<db:/contable/numcon>}*/
		var fs_numcon = databaseManager.getFoundSet('contable','numcon')
		var estado = fs_numcon.find()
		if (estado == false)
		{
			globals.DIALOGS.showWarningDialog('Aviso',"Error al hacer el find","Ok")
			error = 1
		}
		fs_numcon.anio 		= fanio
		fs_numcon.mes  		= fmes
		fs_numcon.empresa 	= globals.gUservID
		if (fs_numcon.search() == 0)
		{	
	        globals.DIALOGS.showWarningDialog('Aviso',"Fecha inválida","Ok")
			error = 1
		}
		else
		{
			if (fs_numcon.marca_cierre == 1)
			{
				globals.DIALOGS.showWarningDialog('Aviso',"Mes Cerrado","Ok")
				error = 1
			}
		}
	}
	if (error == 1)
	{
		globals.DIALOGS.showWarningDialog('Aviso',"Asiento sin actualizar","Ok")		
	}
	else
	{
		numero       = fs_numcon.limbo
		provisorio   = fs_numcon.limbo		
		moneda_carga = 1	
		total        = globals.gtotal_debe
		fs_numcon.limbo = fs_numcon.limbo + 1
		var estado = databaseManager.saveData()
		if (estado == false){
			globals.DIALOGS.showWarningDialog('Aviso',"No se actualizaron los datos","Ok")
			databaseManager.revertEditedRecords()
			return
		}
		globals.DIALOGS.showInfoDialog("Aviso","Asiento actualizado","Ok")
		onShow()
	}
}

/**
 * @param {String} extension
 * @param {String} comienzo_archivo
 * @param {String} comienzo_linea
 * @param {String} marca_txt
 * @param {String} separador
 * @param {String} fin_linea
 * @param {String} fin_archivo
 *
 * @properties={typeid:24,uuid:"E8668851-B657-46B7-8F7F-A3A451C57634"}
 */
function exportaExcel(extension,comienzo_archivo,comienzo_linea,marca_txt,separador,fin_linea,fin_archivo) {
	var $nombre = 'c:/Asientos - ' + globals.glegajo + extension
	var jsFile
	if (application.getApplicationType() == APPLICATION_TYPES.WEB_CLIENT)
	{
		jsFile = plugins.file.createFile($nombre)
	}
	else
	{
		jsFile = plugins.file.showFileSaveDialog($nombre)
	}
	if (jsFile)
	{
		var fw = new Packages.java.io.FileWriter(jsFile.getAbsolutePath());
		var bw = new Packages.java.io.BufferedWriter(fw);
		
		var fs = forms.asiento_cierre_det.foundset
		
		if (comienzo_archivo != '')
		{
			bw.write(comienzo_archivo,0,comienzo_archivo.length)
			bw.newLine()
		}
		//ESCRIBO EL NOMBRE DE LAS COLUMNAS EN LA PRIMER LINEA DEL ARCHIVO
		var linea = comienzo_linea + marca_txt + 'Nº Asiento' + marca_txt + separador + marca_txt + 'Fecha' + marca_txt + separador + marca_txt + 
					'Nº Cuenta' + marca_txt + separador + marca_txt + 'Nombre Cuenta' + marca_txt + separador + marca_txt + 
					'Division' + marca_txt + separador + marca_txt + 'Centro' + marca_txt + separador + marca_txt + 
					'Debe' + marca_txt + separador + marca_txt + 'Haber' + marca_txt + separador + marca_txt + 'Leyenda' + marca_txt + fin_linea
		bw.write(linea,0,linea.length)
		var $ctos = databaseManager.getFoundSetCount(fs)
		
		var i = 1
		while (i <= $ctos)
		{
			var $rcd = fs.getRecord(i)
			linea = comienzo_linea + marca_txt + $rcd.limbo_to_limbo_cab.numero+ marca_txt + separador + marca_txt +utils.dateFormat($rcd.limbo_to_limbo_cab.fecha, 'dd-MM-yyyy') +
					marca_txt + separador + marca_txt + $rcd.limbo_to_cuentas.cuenta_busca + marca_txt + separador + marca_txt + $rcd.limbo_to_cuentas.descripcion +
					marca_txt + separador + marca_txt + $rcd.division + marca_txt + separador + marca_txt + $rcd.centro + marca_txt + separador + marca_txt + 
					utils.numberFormat($rcd.importe_debe,2) + marca_txt + separador + marca_txt + utils.numberFormat($rcd.importe_haber,2) + marca_txt + 
					separador + marca_txt + $rcd.leyenda + marca_txt + fin_linea
			bw.newLine()
			bw.write(linea,0,linea.length)
			i++
		}
		if (fin_archivo != '')
		{
			bw.write(fin_archivo,0,fin_archivo.length)
		}
		bw.close()
		fw.close()

		if (application.getApplicationType() == APPLICATION_TYPES.WEB_CLIENT)
		{
			var mimeType = 'application/vnd.ms-excel'
			if (!plugins.file.writeFile(jsFile.getName(), jsFile.getBytes(), mimeType))
			{
				globals.DIALOGS.showErrorDialog('Error','Ocurrio un error y no se pudo grabar el archivo','OK');
			}
			plugins.file.deleteFile(jsFile.getAbsolutePath())
		}
		else
		{
			application.executeProgram("rundll32.exe", ["url.dll,FileProtocolHandler", jsFile.getAbsolutePath()])
		}
	}
}

/**
 * @properties={typeid:24,uuid:"3B0DA012-A67B-48C8-B080-A5263FB03484"}
 * @AllowToRunInFind
 */
function AsientoCierre() {
	databaseManager.setAutoSave(false)
	/** @type {JSFoundSet<db:/contable/saldos>} */
	var $saldos = databaseManager.getFoundSet('contable','saldos')	
	var estado = $saldos.find()
	if (estado == false)
	{
		globals.DIALOGS.showWarningDialog('Aviso',"Error al hacer el find","Ok")
		//plugins.busy.unblock();				
		return 0
	}
 
	$saldos.anio = '<'+fanio
	$saldos.saldos_to_cuentas.capitulo = 3
	
	$saldos.newRecord()
	
	$saldos.anio = fanio
	$saldos.mes = '<='+fmes
    $saldos.saldos_to_cuentas.capitulo = 3    
	
	fcuantos = $saldos.search()	
	if (fcuantos == 0)
	{
		globals.DIALOGS.showWarningDialog('Aviso','Sin datos','OK')
		//plugins.busy.unblock();				
		return 0
	}
	$saldos.sort('cuentas_id asc, division asc, centro asc')
	globals.gmoneda_consulta = 1
	controller.newRecord()
	tipo_actualizacion 	= globals.z_conf_asiento_cierre
	hizo   				= globals.glegajo
	moneda 				= "A"
	letra  				= " "		
	moneda_carga 		= 1
	texto 				= "Asiento de Cierre"
	fecha 				= new Date(fanio,fmes,gejercicio_to_ejercicios.fecha_fin.getDate(),0,0,0,0)
	fcuantos = databaseManager.getFoundSetCount($saldos)
	var totpes = 0
	var totdol = 0
	globals.gtotal_debe  = 0
	globals.gtotal_haber = 0
	ftotal    = 0
	ftotdol   = 0
	fcuenta   = 0
	fdivision = 0
	for (var i = 1 ; i <= fcuantos ; i++)
	{
		$saldos.setSelectedIndex(i)
		if (i == 1)
		{
		 	fcuenta   = $saldos.cuentas_id
		 	fdivision = $saldos.division
		 	fcentro   = $saldos.centro
		}
		if (fcuenta == $saldos.cuentas_id && fdivision == $saldos.division && fcentro == $saldos.centro)
		{
			totpes += $saldos.debe_pes - $saldos.haber_pes
			totdol += $saldos.debe_dol - $saldos.haber_dol
		}
		else 
		{
			totpes = totpes * (-1)
			totdol = totdol * (-1)
			if (totpes != 0)
			{
				GraboItem(totpes, totdol)
			}
			totpes    = $saldos.debe_pes - $saldos.haber_pes
			totdol    = $saldos.debe_dol - $saldos.haber_dol
		 	fcuenta   = $saldos.cuentas_id
		 	fdivision = $saldos.division
		 	fcentro   = $saldos.centro
		}			
	}
	totpes = totpes * (-1)
	totdol = totdol * (-1)
	if (totpes != 0)
	{
		GraboItem(totpes, totdol)
	}
	var dolaux = ftotal / ftotdol
	dolar = dolaux.toFixed(2)*1
	if (dolar < 1)
	{
		dolar = dolar * (-1)
	}
	if (ftotal != 0)
	{
		limbo_cab_to_limbo.newRecord()
		/** @type {JSFoundSet<db:/contable/ctas_sis>}*/
		var fs_ctas_sis = databaseManager.getFoundSet('contable','ctas_sis')	
		var estado = fs_ctas_sis.find()
		if (estado == false)
		{
			globals.DIALOGS.showWarningDialog('Aviso',"Error al hacer el find","Ok")
			//plugins.busy.unblock();		
			return 0
		}
		fs_ctas_sis.sistema =  1
		fs_ctas_sis.codigo  = 35
		var estado = fs_ctas_sis.search()
		if (estado != 1)
		{
			globals.DIALOGS.showWarningDialog('Aviso',"No ubica la cuenta","Ok")
			//plugins.busy.unblock();		
			return 0
		}
		fs_ctas_sis.setSelectedIndex(1)
		limbo_cab_to_limbo.cuentas_id = fs_ctas_sis.cuentas_id
		limbo_cab_to_limbo.division   = fs_ctas_sis.division
		limbo_cab_to_limbo.centro     = fs_ctas_sis.centro
		limbo_cab_to_limbo.leycod     = 0
		limbo_cab_to_limbo.leyenda    = "Asiento de cierre"
		ftotal  = ftotal  * (-1)
		ftotdol = ftotdol * (-1)
		if (ftotal < 0)
		{
			limbo_cab_to_limbo.columna = "H"
			limbo_cab_to_limbo.importe = ftotal  * (-1)
			limbo_cab_to_limbo.impodol = ftotdol * (-1)
			globals.gtotal_haber = globals.gtotal_haber + (ftotal * (-1))
		}
		else 
		{
			limbo_cab_to_limbo.columna = "D"
			limbo_cab_to_limbo.impodol = ftotdol
			limbo_cab_to_limbo.importe = ftotal
			globals.gtotal_debe += ftotal
		}
	}
	//plugins.busy.unblock();
	forms.asiento_cierre_impresion.ffecha  = fecha
	forms.asiento_cierre_impresion.ftdebe  = globals.gtotal_debe
	forms.asiento_cierre_impresion.fthaber = globals.gtotal_haber
	elements.tabs_80.addTab(forms.asiento_cierre_det,null,null,null,null,null,null,'limbo_cab_to_limbo')
	return 1
}
